<template>
	<view class="container">
		<!-- 头部区域 -->
		<view class="header">
			<view class="logo"></view>
			<view class="">
				<view class="title">社区医疗</view>
				<view class="subtitle">欢迎注册！</view>
			</view>

		</view>

		<!-- 表单区域 -->
		<form class="form">
			<!-- 手机号 -->
			<view class="form-item">
				<text class="label">手机号</text>
				<input type="number" v-model="form.phone" placeholder="请输入登录手机号" @blur="checkPhoneFormat" />
				<text class="error" v-if="phoneError">手机号格式不正确！</text>
			</view>

			<!-- 密码 -->
			<view class="form-item">
				<text class="label">密码</text>
				<input type="password" v-model="form.password" placeholder="设置密码" />
			</view>

			<!-- 确认密码 -->
			<view class="form-item">
				<text class="label">确认密码</text>
				<input type="password" v-model="form.confirmPassword" placeholder="再次输入密码确认" />
			</view>

			<!-- 日期和性别行 -->
			<view class="form-row">
				<!-- 出生日期 -->
				<view class="form-item date">
					<text class="label">出生日期</text>
					<picker mode="date" :value="form.birthday" @change="handleBirthdayChange">
						<view class="picker-display">{{ form.birthday }}</view>
					</picker>
				</view>

				<!-- 性别选择 -->
				<view class="form-item gender">
					<text class="label">性别</text>
					<radio-group :value="form.gender" @change="handleGenderChange">
						<label>
							<radio value="男" /> 男
						</label>
						<label>
							<radio value="女" /> 女
						</label>
					</radio-group>
				</view>
			</view>

			<!-- 身份证 -->
			<view class="form-item">
				<text class="label">居民身份证</text>
				<input type="text" v-model="form.idCard" placeholder="请输入18位身份证号" />
			</view>

			<!-- 姓名 -->
			<view class="form-item">
				<text class="label">姓名</text>
				<input type="text" v-model="form.name" placeholder="请输入姓名" />
			</view>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="handleSubmit">确认注册</button>
		</form>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import md5 from 'js-md5'

// 表单数据类型
interface FormData {
  phone: string
  password: string
  confirmPassword: string
  birthday: string
  gender: '男' | '女'
  idCard: string
  name: string
}

// 表单数据
const form = reactive<FormData>({
  phone: '',
  password: '',
  confirmPassword: '',
  birthday: '1996-11-02',
  gender: '男',
  idCard: '',
  name: ''
})

// 错误状态
const phoneError = ref(false)
const idCardError = ref(false)
const passwordError = ref(false)
const confirmPasswordError = ref(false)
const nameError = ref(false)

// 检查手机号格式
const checkPhoneFormat = () => {
  const reg = /^1[3-9]\d{9}$/
  phoneError.value = !reg.test(form.phone)
  return !phoneError.value
}

// 检查身份证格式
const checkIdCard = () => {
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  idCardError.value = !reg.test(form.idCard)
  return !idCardError.value
}

// 检查密码强度
const checkPassword = () => {
  passwordError.value = form.password.length < 6
  return !passwordError.value
}

// 检查密码一致性
const checkPasswordMatch = () => {
  confirmPasswordError.value = form.password !== form.confirmPassword
  return !confirmPasswordError.value
}

// 检查姓名
const checkName = () => {
  nameError.value = form.name.trim().length < 2
  return !nameError.value
}

// 处理日期选择
const handleBirthdayChange = (e: any) => {
  form.birthday = e.detail.value
}

// 处理性别选择
const handleGenderChange = (e: any) => {
  form.gender = e.detail.value
}

// 提交表单 - 完整实现
const handleSubmit = async () => {
  // 执行所有验证
  const validations = [
    checkPhoneFormat(),
    checkPassword(),
    checkPasswordMatch(),
    checkIdCard(),
    checkName()
  ]
  
  if (validations.some(valid => !valid)) {
    uni.showToast({ title: '请检查表单信息', icon: 'none' })
    return
  }

  uni.showLoading({ title: '注册中...', mask: true })
  
    try {
        // 性别转换：男->1, 女->2
        const genderNum = form.gender === '男' ? 1 : 2
        
        // 准备请求数据
        const requestData = {
          uid: form.idCard,
          name: form.name,
          phone: form.phone,
          gender: genderNum,
          birthday: form.birthday,
          pwdmd5: md5(form.password)
        }
        
        console.log('注册请求数据:', requestData); // 添加日志便于调试
        
        // 发送注册请求 - 修复响应处理
        const response = await uni.request({
          url: "http://localhost:3010/user/register",
          method: 'POST',
          header: { 'Content-Type': 'application/x-www-form-urlencoded' },
          data: requestData
        })
        
        // 更健壮的响应处理（避免解构）
        let res;
        
        // 判断响应结构（可能是数组或对象）
        if (Array.isArray(response)) {
          // 如果是数组，取第二个元素作为响应
          res = response[1] || response[0];
        } else {
          // 如果是对象，直接使用
          res = response;
        }
        
        // 检查响应是否有效
        if (!res) {
          throw new Error('无效的响应');
        }
        
        // 检查HTTP状态码
        if (res.statusCode && res.statusCode !== 200) {
          throw new Error(`服务器错误: ${res.statusCode}`);
        }
        
        // 检查响应数据结构
        if (!res.data) {
          throw new Error('无效的响应格式');
        }
        
        const responseData = res.data;
        
        // 使用更安全的属性访问
        const code = responseData.code;
        const message = responseData.msg || '注册失败';
        
        if (code !== 200) {
          throw new Error(message);
        }
        
        uni.showToast({ title: '注册成功', icon: 'success' })
        
        // 注册成功后跳转到登录页面
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/login/login' })
        }, 1500)
        
      } catch (error) {
        console.error('注册错误:', error);
        
        let message = '注册失败';
        
        if (error.message.includes('Network')) {
          message = '网络连接失败';
        } else if (error.message.includes('服务器错误')) {
          message = error.message;
        } else if (error.message) {
          message = error.message;
        }
        
        uni.showToast({ title: message, icon: 'none' })
      } finally {
        uni.hideLoading();
      }
    }
</script>

<style scoped>
	/* 全局容器 */
	.container {
		padding: 30rpx;
		background-color: #fff;
	}

	/* 头部样式 */
	.header {
		margin-bottom: 40rpx;
		display: flex;
	}

	.logo {
		width: 200rpx;
		height: 200rpx;
		background-color: #83ffc3;
		border-radius: 30rpx;
		margin-bottom: 15rpx;
		margin-right: 30rpx;
	}

	.title {
		font-size: 34rpx;
		color: #666;
		margin: 30rpx 0rpx;
	}

	.subtitle {
		
		font-size: 42rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	/* 表单通用样式 */
	.form-item {
		margin-bottom: 35rpx;
	}

	.label {
		display: block;
		font-size: 32rpx;
		margin-bottom: 12rpx;
		color: #333;
		font-weight: 700;
	}

	input {
		width: 100%;
		height: 68rpx;
		line-height: 68rpx;
		border-bottom: 1px solid #02d36e;
		padding: 0 15rpx;
		box-sizing: border-box;
		font-size: 26rpx;
	}

	/* 错误提示 */
	.error {
		color: red;
		font-size: 24rpx;
		margin-top: 8rpx;
		display: block;
	}

	/* 行布局（日期+性别） */
	.form-row {
		display: flex;
		justify-content: space-between;
	}

	.date,
	.gender {
		width: 48%;
	}

	/* 日期选择器显示 */
	.picker-display {
		width: 100%;
		height: 68rpx;
		line-height: 68rpx;
		border-bottom: 1px solid #eee;
		padding: 0 15rpx;
		box-sizing: border-box;
		font-size: 26rpx;
		color: #999;
	}

	/* 性别选择 */
	.gender radio-group {
		display: flex;
		align-items: center;
		height: 68rpx;
		border-bottom: 1px solid #eee;
		padding-left: 15rpx;
		box-sizing: border-box;
	}

	.gender label {
		margin-right: 40rpx;
		font-size: 26rpx;
	}

	/* 提交按钮 */
	.submit-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background: #00d36d;
		color: #fff;
		font-size: 40rpx;
		font-weight: 700;
		border-radius: 10rpx;
	}
	.error {
	  color: #e64340;
	  font-size: 24rpx;
	  margin-top: 8rpx;
	  display: block;
	}
	
	/* 添加错误输入框样式 */
	input.error-border {
	  border-bottom-color: #e64340;
	}
</style>